﻿using WebApplication1.Core.DataTransferObject;
using WebApplication1.Core.Domain.Entities;
using WebApplication1.Core.Domain.RepositoryContracts;
using WebApplication1.Core.ServiceContracts;

namespace WebApplication1.Core.Services {
    public class SheQuService : ISheQuService {

        private readonly ISheQuRepository _sheQuRepository;

        public SheQuService(ISheQuRepository sheQuRepository) {
            _sheQuRepository = sheQuRepository;
        }

        public async Task<SheQuResponse> AddSheQu(SheQuRequest? sheQuAddRequest) {
            if(sheQuAddRequest == null) {
                throw new ArgumentNullException(nameof(sheQuAddRequest));
            }
            SheQu temp = sheQuAddRequest.ToSheQu();
            //temp.SheQuID = Guid.NewGuid();
            SheQu addedSheQu = await _sheQuRepository.AddSheQu(temp);
            return addedSheQu.ToSheQuResponse();
        }

        public async Task<bool> DeleteSheQu(ushort? shequID) {
            if(shequID == null) { throw new ArgumentNullException(nameof(shequID)); }
            bool result = await _sheQuRepository.DeleteSheQu(shequID.Value);
            return result;
        }

        public async Task<IEnumerable<SheQuResponse>> GetAllSheQu() {
            IEnumerable<SheQu> allSheQu = await _sheQuRepository.GetAllSheQu();
            return allSheQu.Select(shequ => shequ.ToSheQuResponse());
        }

        public async Task<IEnumerable<SheQuResponse>?> GetSheQuByMingCheng(string? mingCheng) {
            if(mingCheng == null) { throw new ArgumentNullException(nameof(mingCheng)); }
            IEnumerable<SheQu> filterResult = await _sheQuRepository.GetFilteredSheQu(shequ => shequ.MingCheng.Contains(mingCheng));
            return filterResult.Select(temp => temp.ToSheQuResponse());
        }

        public async Task<SheQuResponse?> GetSheQuBySheQuID(ushort? shequID) {
            if(shequID == null) { throw new ArgumentNullException(nameof(shequID)); }
            SheQu? result = await _sheQuRepository.GetSheQuBySheQuID(shequID.Value);
            return result?.ToSheQuResponse();
        }

        public async Task<SheQuResponse?> UpdateSheQu(SheQuRequest? sheQuUpdateRequest) {
            if(sheQuUpdateRequest == null) { throw new ArgumentNullException(nameof(sheQuUpdateRequest)); }
            bool isSuccess = await _sheQuRepository.UpdateSheQu(sheQuUpdateRequest.ToSheQu());
            if(isSuccess) {
                return sheQuUpdateRequest.toSheQuResponse();
            } else {
                return null;
            }
        }
    }
}
